
% uses image registration to correct for drift in an IOS movie; note that
% this can be quite slow;
%
% inputs:
% mov: the movie to be stabilized
% refframe: the frame of the movie to use as a reference; if not specificied then will default to frame 1
% imtrans: if you previously used this function to calculate the
% translation, then you can put in that transformation array and apply it
% to the inputed movie
%
% transformtype is an optional parameter that will allow selection of a
% particular transform type; default is translation
%
% outputs:
% r: the drift corrected movie
% imtrans: an array of the transformation matricies (affine2d objects) used
% to transform the movie

function [r,imtrans] = driftCorrectWidefield(mov,refframe,imtrans,transformtype,regconfig)

if nargin < 5 || isempty(regconfig)
    regconfig = "monomodal";
end

if nargin < 4 || isempty(transformtype)
    transformtype = 'translation';
end

subimrange = [.28,1-.28];
mi = round([subimrange(1)*size(mov,1),subimrange(2)*size(mov,1)]);
ni = round([subimrange(1)*size(mov,2),subimrange(2)*size(mov,2)]);


%normalize each frame in the movie:
Xmin = min(mov(:));
Xmax = max(mov(:));
movN = (mov-Xmin)./(Xmax-Xmin);

submov = movN(mi(1):mi(2),ni(1):ni(2),:);

if nargin < 2 || isempty(refframe)
    fixedframe = submov(:,:,1);
elseif numel(refframe) == 1
    fixedframe = submov(:,:,refframe);
else
    fixedframe = refframe(mi(1):mi(2),ni(1):ni(2),:);       %this is if you want to input some specific image to align to
end
[optimizer, metric] = imregconfig(regconfig);

r = mov;
f = waitbar(0,'percent movie registered');
if nargin < 3 || isempty(imtrans)
    imtrans = [];
    for n = 1:size(mov,3)
        tf = imregtform(submov(:,:,n),fixedframe,transformtype,...
            optimizer,metric);
        imtrans = [imtrans,tf];
        r(:,:,n) = imwarp(r(:,:,n),tf,'OutputView',imref2d([size(mov,1),size(mov,2)]));
        waitbar(n/size(mov,3),f);
    end
elseif nargin > 2 && ~isempty(imtrans)
    for n = 1:size(mov,3)
        r(:,:,n) = imwarp(r(:,:,n),imtrans(n),'OutputView',imref2d([size(mov,1),size(mov,2)]));
        waitbar(n/size(mov,3),f);
    end
end
    
        
close(f)
